import { useEffect, useState, useRef } from 'react'
function Content(props) {
    /*      let [listItems, setListItems] =useState([]) */
    let [index, setIndex] = useState(-1)
    let [textVal, setTextVal] = useState('')
    const inputEl = useRef(null);
    //修改单个状态
    function changeChecked(id, event) {
        props.changeChecked(id, event.target.checked)

    }
    //删除某一项
    function deleteItem(id) {
        props.deleteItem(id)
    }
    //全选或全不选
    function changeAllItems(e) {
        props.changeAllItems(e.target.checked)
    }
    //打开编辑框
    function openEdit(id, val) {
        setIndex(id)
        setTextVal(val)
       setTimeout(function () {
        inputEl.current?.focus()
     /*        inputEl.current?.focus({
                cursor: 'start',
            }); */
        }, 10); 

    }
    //失去焦点关闭编辑框
    function closeEdit(id) {
        props.confirm(id, textVal)
        setIndex(-1)
    }
    //回车关闭编辑框
    function enterEdit(e, id) {
        if (e.keyCode == 13) {
            props.confirm(id, textVal)
            setIndex(-1)
        }
    }
    //将修改后的状态保存
    function getVal(e) {
        setTextVal(e.target.value)
    }
    useEffect(() => {
    })
    return (
        <>
            <section className="main">
                {/* defaultChecked只会设置一次，解决办法加key，且值要和defaultChecked一样 */}
                <input id="toggle-all" className="toggle-all" type="checkbox" onChange={changeAllItems} defaultChecked={props.computed ? props.todoList.length > 0 : false} key={props.computed ? props.todoList.length > 0 : false} />
                <label htmlFor="toggle-all">Mark all as complete</label>
                <ul className="todo-list">
                    {
                        props.filterList.map(item =>
                            <li key={item.id} className={`todo ${item.isChecked ? 'completed' : ''}`} >
                                <div onDoubleClick={() => openEdit(item.id, item.text)} style={{ display: (index != item.id ? 'block' : 'none') }} >
                                    <input className="toggle" type="checkbox" defaultChecked={item.isChecked} key={item.isChecked} onChange={() => changeChecked(item.id, event)} />
                                    <label>{item.text}</label>
                                    <button className="destroy" onClick={() => deleteItem(item.id)} />
                                </div>
                                <input ref={index == item.id ?inputEl:null } className="edit" type="text" style={{ display: (index == item.id ? 'block' : 'none') }} onBlur={() => { closeEdit(item.id) }} onKeyUp={(e) => { enterEdit(e, item.id) }} value={textVal} onChange={getVal} />
                            </li>
                        )
                    }
                </ul>
            </section>
        </>
    )


}

export default Content